package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.enums.AccBillStatusEnum;
import cn.huiyunche.base.service.enums.AccPaytypeEnum;
import cn.huiyunche.base.service.enums.AccTurnoverStatusEnum;
import cn.huiyunche.base.service.enums.FrozenStateEnum;
import cn.huiyunche.base.service.framework.security.JwtAuthenicationFilter;
import cn.huiyunche.base.service.interfaces.*;
import cn.huiyunche.base.service.mappers.CBalanceMapper;
import cn.huiyunche.base.service.mappers.ext.CBalanceViewMapper;
import cn.huiyunche.base.service.model.*;
import cn.huiyunche.base.service.utils.DateUtils;
import cn.huiyunche.base.service.vo.Result;
import cn.huiyunche.base.service.vo.UserShowVo;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * 账户余额接口实现类
 *
 * @author lm
 */
@Service
public class CAccntBalanceServiceImpl implements CAccntBalanceService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CAccntBalanceServiceImpl.class);

    @Autowired
    private UserService userService = null;

    @Autowired
    private CBalanceMapper cBalanceMapper = null;

    @Autowired
    private CBalanceViewMapper cBalanceViewMapper = null;

    @Autowired
    private Md5PasswordEncoder passwordEncoder = null;

    @Autowired
    private JwtAuthenicationFilter jwtAuthenticationFilter = null;

    @Autowired
    private SendMessageService sendMessageService = null;

    @Autowired
    private CAccntTurnOverService cAccntTurnOverService = null;

    @Autowired
    private CAccntBillService cAccntBillService = null;

    @Autowired
    private CodeService codeService = null;

    private CodeService getCodeService() {
        return this.codeService;
    }

    private CAccntBillService getCAccntBillService() {
        return this.cAccntBillService;
    }

    private UserService getUserService() {
        return this.userService;
    }

    private CBalanceMapper getCBalanceMapper() {
        return this.cBalanceMapper;
    }

    private SendMessageService getSendMessageService() {
        return this.sendMessageService;
    }

    private CBalanceViewMapper getcBalanceViewMapper() {
        return this.cBalanceViewMapper;
    }

    private CAccntTurnOverService getcAccntTurnOverService() {
        return this.cAccntTurnOverService;
    }

    // 查询当前登录用户
    public UserShowVo getUserShowVo() {
        try {
            return this.getUserService().getCurrentUser();
        } catch (Exception e) {
            LOGGER.error("select current user ERROR : {}.", e);
            throw new BusinessException("查询当前登录用户异常");
        }
    }

    /**
     * 第一次设置密码／忘记密码 － 设置密码
     *
     * @param pwd
     * @return
     */
    @Override
    public Result<Object> addOrUpdatePwd(String pwd) {
        Date currentTime = new Date();
        LOGGER.info("balance set passowrd ServiceImpl.pwd:{}.", pwd);
        Result<Object> result = new Result<>();

        try {
            // 查询当前用户
            UserShowVo userShowVo = this.getUserShowVo();
            if (null == userShowVo) {
                result.setSuccess(false);
                result.setMessage("当前登录账户不存在!");
                return result;
            }
            // 根据用户id 和 用户类型 查询账户余额表用户信息
            Long userId = userShowVo.getId();
            pwd = passwordEncoder.encodePassword(pwd, jwtAuthenticationFilter.getSecureKey());
            LOGGER.info("balance set password, md5 after password:{}.", pwd);
            CBalance cBalance = this.getAccntLedger(userId, userShowVo.getUserType());
            if (null == cBalance) {
                // 查询账户余额表没有该用户信息的时候, 插入一条新的纪录并记录密码
                CBalance newCBalance = new CBalance();
                newCBalance.setUserId(userId);
                newCBalance.setUserName(userShowVo.getRealName() != null ? userShowVo.getRealName() : "");
                newCBalance.setUserType(userShowVo.getUserType());
                newCBalance.setPwd(pwd);
                newCBalance.setCreateTime(currentTime);
                newCBalance.setUpdateTime(currentTime);
                this.getCBalanceMapper().insertSelective(newCBalance);
                LOGGER.info("balance set password success insert new balance.userId:{}.", userId);

                result.setSuccess(true);
                result.setMessage("设置提现密码成功.");
                return result;
            }
            String password = cBalance.getPwd();
            if (StringUtils.isEmpty(password)) {
                // 第一次设置密码
                int count = this.setAccntLedgerPwd(cBalance, pwd);
                LOGGER.info("balance set password first set password finish {} count, userId:{}.", count, userId);
                result.setMessage("设置密码成功.");
            } else {
                // 修改密码
                int count = this.setAccntLedgerPwd(cBalance, pwd);
                LOGGER.info("balance set password update password finish {} count, userId:{}.", count, userId);
                result.setMessage("修改密码成功.");
            }
            result.setSuccess(true);
        } catch (Exception e) {
            LOGGER.error("balance set password error : {}.", e);
            result.setSuccess(false);
            result.setMessage("设置用户密码异常.");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发送验证码
     */
    @Override
    public Result<String> sendCaptcha(String phone, int usertype) {
        Result<String> result = new Result<>(true, "发送成功！");
        try {
            result.setMessage(this.getSendMessageService().sendCaptcha(phone, usertype));
            LOGGER.info("balance set password sendCaptcha finish.");
        } catch (Exception e) {
            LOGGER.error("balance set password sendCaptcha error : {}.", e);
            result.setSuccess(false);
            result.setMessage("设置提现密码,发送验证码异常.");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 查询当前用户的账户余额
     */
    @Override
    public Result<Map<String, Object>> getBalances() {
        LOGGER.info("select current user balance.");
        Result<Map<String, Object>> result = new Result<Map<String, Object>>(true, "查询成功！");
        Map<String, Object> map = new HashMap<>();
        map.put("remarks", "每周四，0：00-23：59为提现日，提现需要支付手续费（单笔2元）");
        try {
            // 查询当前用户
            UserShowVo userShowVo = this.getUserShowVo();
            if (null == userShowVo) {
                result.setSuccess(false);
                result.setMessage("当前登录账户不存在!");
                return result;
            }

            // 根据用户id 和 用户类型 查询账户余额表用户信息
            Long userId = userShowVo.getId();
            Integer userType = userShowVo.getUserType();
            LOGGER.info("select current user balance userId:{}.", userId);
            CBalance cBalance = this.getAccntLedger(userId, userType);
            if (null == cBalance) {
                map.put("balance", BigDecimal.ZERO);
                map.put("withdrawalBalance", BigDecimal.ZERO);
                map.put("phone", userShowVo.getName());
                map.put("openid", userShowVo.getOpenId());
                map.put("billStatus", 20);
                LOGGER.info("select current user balance is null.");
                result.setData(map);
            } else {
                CBillExample billExample = new CBillExample();
                billExample.createCriteria().andUserIdEqualTo(userId).andUserTypeEqualTo(userType).andStatusEqualTo(AccBillStatusEnum.WAIT.getValue());
                List<CBill> bills = this.getCAccntBillService().selectByExample(billExample);
                if (bills.size() > 0) {
                    map.put("billStatus", 10);
                } else {
                    map.put("billStatus", 20);
                }
                BigDecimal balance = cBalance.getBalance();
                BigDecimal withdrawalBalance = cBalance.getWithdrawalBalance();
                String phone = cBalance.getPhone();
                if (balance == null || balance.compareTo(BigDecimal.ZERO) == 0) {
                    balance = BigDecimal.ZERO;
                }
                if (withdrawalBalance == null || withdrawalBalance.compareTo(BigDecimal.ZERO) == 0) {
                    withdrawalBalance = BigDecimal.ZERO;
                }
                map.put("balance", balance);
                map.put("withdrawalBalance", withdrawalBalance);
                map.put("phone", phone);
                map.put("openid", cBalance.getOpenid());
                LOGGER.info("select current user balance : {}.", balance);
                result.setData(map);
            }
        } catch (Exception e) {
            LOGGER.error("select current user balance error : {}.", e);
            result.setSuccess(false);
            result.setMessage("系统异常.");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 微信提现－暂时没用
     */
    @Override
    public Result<Object> withdrawal(BigDecimal amount, String openid, String pwd) {
        LOGGER.info("账户提现申请.参数:amount:{},openid:{},pwd:{}.", amount, openid, pwd);
        Result<Object> result = new Result<>();
        try {
            // 查询当前用户
            UserShowVo userShowVo = this.getUserShowVo();
            if (null == userShowVo) {
                LOGGER.info("账户提现申请.当前登录账户不存在.");
                result.setSuccess(false);
                result.setMessage("当前登录账户不存在.");
                return result;
            }
            CBalance cBalance = this.getAccntLedger(userShowVo.getId(), userShowVo.getUserType());
            pwd = passwordEncoder.encodePassword(pwd, jwtAuthenticationFilter.getSecureKey());
            BigDecimal wBalance = cBalance.getWithdrawalBalance();
            if (cBalance != null && cBalance.getPwd().equals(pwd)) {
                if (wBalance != null && amount.compareTo(wBalance) == 1) {
                    LOGGER.info("账户提现申请.提现金额不能大于可提现金额.");
                    result.setSuccess(false);
                    result.setMessage("提现金额不能大于可提现金额.");
                    return result;
                }
                // result = this.getPayTransferService().accTransferBywx(amount, openid);
            } else {
                LOGGER.info("账户提现申请.提现密码不正确.");
                result.setSuccess(false);
                result.setMessage("提现密码不正确.");
                return result;
            }
        } catch (Exception e) {
            LOGGER.info("账户提现申请.系统异常.");
            result.setSuccess(false);
            result.setMessage("系统异常.");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 验证用户输入密码是否正确
     */
    @Override
    public Result<String> checkPwd(String pwd) {
        Date currentTime = new Date();
        LOGGER.info("修改密码,验证原密码是否正确.pwd:{}.", pwd);
        Result<String> result = new Result<String>(true, "密码正确.");
        try {
            // 查询当前用户
            UserShowVo userShowVo = this.getUserShowVo();
            if (null == userShowVo) {
                LOGGER.info("账户提现申请.当前登录账户不存在.");
                result.setSuccess(false);
                result.setData("F");
                result.setMessage("当前登录账户不存在.");
                return result;
            }

            Long userId = userShowVo.getId();
            Integer userType = userShowVo.getUserType();

            // 判断每天每人 不能提现超过3次
            /**
             Result<String> re = this.getcAccntTurnOverService().valWithdrawalLe3(userId, userType);
             if(!re.isSuccess()){
             return re;
             } */
            /** boolean flag = this.getcAccntTurnOverService().valWithdrawalLe3(userId, userType);
             if(!flag){
             result.setSuccess(false);
             result.setData("F");
             result.setMessage("提现次数超过3次");
             return result;
             } */

            CBalance cBalance = this.getAccntLedger(userId, userType);
            pwd = passwordEncoder.encodePassword(pwd, jwtAuthenticationFilter.getSecureKey());
            if (cBalance != null) {
                Integer accountState = cBalance.getUserStatus();
                Date frozenDate = cBalance.getFrozenDate();
                if (!(cBalance.getPwd().equals(pwd))) {
                    // 设置密码错误输入次数，输入错误密码到达5次 账户锁定
                    int errorNum = cBalance.getErrorNum();
                    if (accountState != null && accountState == FrozenStateEnum.FROZEN.getValue() && errorNum >= 5) {
                        result.setSuccess(false);
                        result.setData("F");
                        result.setMessage("账户输入密码错误，未解锁。");

                        cBalance.setErrorNum(errorNum + 1);
                        cBalance.setFrozenDate(currentTime);
                        cBalance.setUserStatus(FrozenStateEnum.FROZEN.getValue());
                        this.getCBalanceMapper().updateByPrimaryKey(cBalance);
                    } else {
                        cBalance.setErrorNum(errorNum + 1);
                        cBalance.setFrozenDate(currentTime);
                        // cBalance.setUserStatus(FrozenStateEnum.FROZEN.getValue());
                        this.getCBalanceMapper().updateByPrimaryKey(cBalance);
                    }

                    result.setSuccess(false);
                    result.setData("F");
                    result.setMessage("密码错误,请重新输入.");
                } else {
                    // 如果输入密码与原密码匹配，则判断用户当前是否锁定状态
                    // 如果是锁定状态 判断时间时间是否到达 半小时 如果超过半小时则 跳转正确页面 解锁时间写上 修改锁定状态
                    if (accountState != null && accountState == FrozenStateEnum.FROZEN.getValue()) {
                        Long diffMin = DateUtils.getDiffMin(frozenDate);
                        if (diffMin <= 30) {
                            result.setSuccess(false);
                            result.setData("F");
                            result.setMessage("账户未解锁。");
                        }
                    } else {
                        result.setData("T");
                        cBalance.setErrorNum(0);
                        cBalance.setUnfrozenDate(currentTime);
                        cBalance.setUserStatus(FrozenStateEnum.UNFROZEN.getValue());
                        this.getCBalanceMapper().updateByPrimaryKey(cBalance);
                    }
                }
            } else {
                result.setSuccess(false);
                result.setData("F");
                result.setMessage("账户不存在.");
            }
        } catch (Exception e) {
            LOGGER.error("验证密码是否正确.系统异常.", e);
            result.setSuccess(false);
            result.setData("F");
            result.setMessage("系统异常.");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 更新账户余额
     */
    @Override
    public Result<String> updatePwd(String pwd) {
        LOGGER.info("修改密码,输入新密码.pwd:{}.", pwd);
        Result<String> result = new Result<>(true, "修改密码成功.");
        try {
            // 查询当前用户
            UserShowVo userShowVo = this.getUserShowVo();
            if (null == userShowVo) {
                LOGGER.info("账户提现申请.当前登录账户不存在.");
                result.setSuccess(false);
                result.setMessage("当前登录账户不存在.");
                return result;
            }
            if (StringUtils.isEmpty(pwd)) {
                LOGGER.info("账户提现申请.密码不能为空.");
                result.setSuccess(false);
                result.setMessage("密码不能为空.");
                return result;
            }
            CBalance cBalance = this.getAccntLedger(userShowVo.getId(), userShowVo.getUserType());
            pwd = passwordEncoder.encodePassword(pwd, jwtAuthenticationFilter.getSecureKey());
            cBalance.setPwd(pwd);

            int updateCount = this.getCBalanceMapper().updateByPrimaryKeySelective(cBalance);
            LOGGER.info("修改密码成功{}条记录.", updateCount);
        } catch (Exception e) {
            LOGGER.error("修改密码,系统异常.", e);
            result.setSuccess(false);
            result.setMessage("系统异常.");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 添加账户
     * 或者新增账户余额
     */
    @Override
    public boolean insertOrUpdateRecord(CBalance cBalance) {
        LOGGER.info("add user balance cBalance : {}.", JSON.toJSONString(cBalance));
        boolean flag = false;
        try {
            int count = this.getcBalanceViewMapper().insertOrUpdate(cBalance);
            LOGGER.info("add user balance cBalance : {}, count : {}.", JSON.toJSONString(cBalance), count);

            flag = true;
        } catch (Exception e) {
            LOGGER.error("add user balance cBalance : {}, error : {}", JSON.toJSONString(cBalance), e);
            throw new BusinessException("更新用户余额异常");
        }
        return flag;
    }

    /**
     * 判断当前用户 是否设置提现密码
     */
    @Override
    public Result<String> isExistPwd() {
        LOGGER.info("判断登录用户是否已经设置提现密码ServiceImpl.");
        // 查询当前用户
        Result<String> result = new Result<String>(true, "查询成功.");
        UserShowVo userShowVo = this.getUserShowVo();
        if (null == userShowVo) {
            result.setSuccess(false);
            result.setMessage("当前登录账户不存在!");
            return result;
        }
        CBalance accntLedger = this.getAccntLedger(userShowVo.getId(), userShowVo.getUserType());
        if (accntLedger != null && !StringUtils.isEmpty(accntLedger.getPwd())) {
            result.setSuccess(true);
            result.setData("T");
            result.setMessage("该用户已经设置提现密码.");
        } else {
            result.setSuccess(true);
            result.setData("F");
            result.setMessage("该用户未设置提现密码.");
        }
        return result;
    }

    /**
     * 司机－银行卡提现
     * 银行卡提现，提现申请成功 账户扣减金额
     *
     * @param amount    金额
     * @param pwd       密码
     * @param quickcash 是否是快速提现 0:不是 1:是
     * @param score     是否是快速提现 0:不使用 1:使用
     * @return
     */
    @Override
    public Result<Object> withdrawalByCard(BigDecimal amount, Integer quickcash, Integer score, String pwd) {
        LOGGER.info("withdrawalByCard params : {}, {}, {}, {}", amount, quickcash, score, pwd);
        Result<Object> result = new Result<Object>(true, "可以提现.");

        // 查询当前用户
        UserShowVo userShowVo = this.getUserShowVo();
        if (null == userShowVo) {
            LOGGER.info("账户提现申请.当前登录账户不存在.");
            result.setSuccess(false);
            result.setMessage("当前登录账户不存在.");
            return result;
        }
        Long userId = userShowVo.getId();
        Integer userType = userShowVo.getUserType();

        Result<Object> re = this.getcAccntTurnOverService().valWithdrawalLe3(amount.abs(), userId, userType);
        if (!re.isSuccess()) {
            return re;
        }

        CBalance cBalance = this.getAccntLedger(userId, userType);
        pwd = passwordEncoder.encodePassword(pwd, jwtAuthenticationFilter.getSecureKey());
        if (cBalance == null || !cBalance.getPwd().equals(pwd)) {
            LOGGER.info("账户提现申请.提现密码不正确.");
            result.setSuccess(false);
            result.setMessage("提现密码不正确.");
            return result;
        }
        BigDecimal wBalance = cBalance.getWithdrawalBalance();
        Result<Object> validationBalance = this.validationBalance(wBalance, amount);
        if (!validationBalance.isSuccess()) {
            return validationBalance;
        }
        try {
            Date currentTime = new Date();
            List<CTurnover> list = new ArrayList<CTurnover>();
            CTurnover cTurnover = new CTurnover();
            cTurnover.setUserId(userId);
            cTurnover.setUserName(userShowVo.getRealName());
            cTurnover.setUserType(userType);
            cTurnover.setPayType(AccPaytypeEnum.WITHDRAWAL.getValue()); // 业务类型 提现
            cTurnover.setOrderId(null);
            cTurnover.setUpdateTime(currentTime);
            cTurnover.setCreateTime(currentTime);
            cTurnover.setStatus(AccTurnoverStatusEnum.DONE.getValue()); // 添加状态 30提现已完成
            cTurnover.setOrderFee(amount.abs().negate());
            cTurnover.setOrderActPay(amount.abs().negate());
            list.add(cTurnover);
            this.getcAccntTurnOverService().addDetailsAndLedger(list, 0);

        } catch (Exception e) {
            LOGGER.info("系统异常.");
            result.setSuccess(false);
            result.setData(BigDecimal.ZERO);
            result.setMessage("系统异常.");
            throw new BusinessException("提现业务处理异常");
        }
        return result;
    }
    /** @Override public Result<Object> withdrawalByCard(BigDecimal amount, Integer quickcash, Integer score, String pwd) {
    LOGGER.info("withdrawalByCard params : {}, {}, {}, {}", amount, quickcash, score, pwd);
    BigDecimal fee = BigDecimal.ZERO;
    BigDecimal subfee = BigDecimal.ZERO;
    BigDecimal actualfee = BigDecimal.ZERO;
    BigDecimal scores = BigDecimal.ZERO;
    Result<Object> result = new Result<Object>(true, "可以提现.");

    // 查询当前用户
    UserShowVo userShowVo = this.getUserShowVo();
    if(null == userShowVo){
    LOGGER.info("账户提现申请.当前登录账户不存在.");
    result.setSuccess(false);
    result.setMessage("当前登录账户不存在.");
    return result;
    }
    Long userId = userShowVo.getId();
    Integer userType = userShowVo.getUserType();

    if(amount.abs().compareTo(BigDecimal.valueOf(20000)) == 1){
    LOGGER.info("提现金额不能大于2万");
    result.setSuccess(false);
    result.setMessage("提现金额不能大于2万");
    return result;
    } else {
    Result<Object> re = this.getcAccntTurnOverService().valWithdrawalLe3(amount.abs(), userId, userType);
    if(!re.isSuccess()){
    return re;
    }
    }
    if(quickcash == 1 ){
    Map<String, Object> withdrawalFeeMap = this.getBScoresService().selectWithdrawalFee(amount);
    fee = (BigDecimal)withdrawalFeeMap.get("fee"); // 快速提现 总手续费
    subfee = (BigDecimal)withdrawalFeeMap.get("subfee"); // 使用积分扣除 金额
    scores = (BigDecimal)withdrawalFeeMap.get("scores"); // 使用积分数

    fee = fee.abs();
    subfee = subfee.abs();
    scores = scores.abs();

    if(score == 1){
    actualfee = amount.abs().subtract(fee).setScale(BIGDECIMAL_POINT, BIGDECIMAL_TYPE).add(subfee).setScale(BIGDECIMAL_POINT, BIGDECIMAL_TYPE);
    } else{
    actualfee = amount.abs().subtract(fee).setScale(BIGDECIMAL_POINT, BIGDECIMAL_TYPE);
    }

    result.setData(actualfee);
    }
    Date currentTime = new Date();

    if(quickcash == 0){
    // 普通提现 每周四提现
    String weekOfDate = DateUtils.getWeekOfDate(currentTime);
    if(!"星期四".equals(weekOfDate)){
    LOGGER.info("账户提现日为每周四.");
    result.setSuccess(false);
    result.setMessage("账户提现日为每周四.");
    return result;
    }
    }

    CBalance cBalance = this.getAccntLedger(userId, userType);
    pwd = passwordEncoder.encodePassword(pwd, jwtAuthenticationFilter.getSecureKey());
    if(cBalance != null && cBalance.getPwd().equals(pwd)){
    BigDecimal wBalance = cBalance.getWithdrawalBalance();
    BigDecimal balance = cBalance.getBalance();
    if(quickcash == 1){
    Result<Object> validationBalance = this.validationBalance(balance, amount);
    if(!validationBalance.isSuccess()){
    return validationBalance;
    }
    } else{
    Result<Object> validationBalance = this.validationBalance(wBalance, amount);
    if(!validationBalance.isSuccess()){
    return validationBalance;
    }
    }
    try {
    List<CTurnover> list = new ArrayList<CTurnover>();
    CTurnover cTurnover = new CTurnover();
    cTurnover.setUserId(userId);
    cTurnover.setUserName(userShowVo.getRealName());
    cTurnover.setUserType(userType);
    cTurnover.setPayType(AccPaytypeEnum.WITHDRAWAL.getValue()); // 业务类型 提现
    cTurnover.setOrderId(null);
    cTurnover.setUpdateTime(currentTime);
    cTurnover.setCreateTime(currentTime);
    cTurnover.setStatus(AccTurnoverStatusEnum.DONE.getValue()); // 添加状态 30提现已完成
    cTurnover.setOrderFee(amount.abs().negate());
    cTurnover.setOrderActPay(amount.abs().negate());
    if(quickcash == 1){
    cTurnover.setOrderActPay(actualfee.abs().negate());
    }
    list.add(cTurnover);
    this.getcAccntTurnOverService().addDetailsAndLedger(list, quickcash);

    // 扣除积分
    if(quickcash == 1 && score == 1){
    BScoresTurnover bScoresTurnover = new BScoresTurnover();
    bScoresTurnover.setUserId(userId);
    bScoresTurnover.setUserName(userShowVo.getRealName());
    bScoresTurnover.setUserType(userType);
    bScoresTurnover.setBusinessId(null);
    bScoresTurnover.setBusinessType(AccPaytypeEnum.WITHDRAWAL.getValue());
    bScoresTurnover.setScore(scores.abs().negate());
    bScoresTurnover.setCost(subfee);
    bScoresTurnover.setCreateTime(new Date());
    bScoresTurnover.setUpdateTime(new Date());
    bScoresTurnover.setIsused(true);

    this.getBScoresTurnoverService().insert(bScoresTurnover, true);
    }
    } catch (Exception e) {
    LOGGER.info("系统异常.");
    result.setSuccess(false);
    result.setData(BigDecimal.ZERO);
    result.setMessage("系统异常.");
    e.printStackTrace();
    }
    } else{
    LOGGER.info("账户提现申请.提现密码不正确.");
    result.setSuccess(false);
    result.setMessage("提现密码不正确.");
    return result;
    }
    return result;
    } */

    /**
     * 验证用户余额 是否够提现
     *
     * @param balance
     * @param amount
     * @return
     */
    public Result<Object> validationBalance(BigDecimal balance, BigDecimal amount) {
        LOGGER.info("validationBalance param : {}, {}", balance, amount);
        Result<Object> result = new Result<Object>(true, "true");
        if (balance == null) {
            LOGGER.info("账户提现申请.提现金额不能大于可提现金额.");
            result.setSuccess(false);
            result.setMessage("提现金额不能大于可提现金额.");
            return result;
        } else if (balance != null && amount.abs().compareTo(balance) == 1) {
            LOGGER.info("账户提现申请.提现金额不能大于可提现金额.");
            result.setSuccess(false);
            result.setMessage("提现金额不能大于可提现金额.");
            return result;
        } else if (amount.abs().compareTo(BigDecimal.ZERO) != 1) {
            LOGGER.info("账户提现申请.提现金额须大于0.");
            result.setSuccess(false);
            result.setMessage("账户提现申请.提现金额须大于0.");
            return result;
        }
        return result;
    }

    /**
     * 提现失败 添加流水记录
     */
    @Override
    public Result<String> upBalanceByWithdrawal(Long id, BigDecimal amount, String pwd) {
        LOGGER.info("upBalanceByWithdrawal param : {}, {}, {}", id, amount, pwd);
        Date currentTime = new Date();
        Result<String> result = new Result<String>(true, "修改余额成功.");
        // 查询当前用户
        UserShowVo userShowVo = this.getUserShowVo();
        if (null == userShowVo) {
            LOGGER.info("账户提现修改余额.当前登录账户不存在.");
            result.setSuccess(false);
            result.setData("F");
            result.setMessage("当前登录账户不存在.");
            return result;
        }
        CBalance cBalance = this.getAccntLedger(userShowVo.getId(), userShowVo.getUserType());
        pwd = passwordEncoder.encodePassword(pwd, jwtAuthenticationFilter.getSecureKey());
        if (cBalance != null && cBalance.getPwd().equals(pwd)) {
            try {
                List<CTurnover> list = new ArrayList<CTurnover>();
                CTurnover cTurnover = new CTurnover();
                cTurnover.setUserId(userShowVo.getId());
                cTurnover.setUserName(userShowVo.getRealName());
                cTurnover.setUserType(userShowVo.getUserType());
                cTurnover.setPayType(AccPaytypeEnum.WITHDRAWAL.getValue());
                cTurnover.setOrderId(id);
                cTurnover.setOrderFee(amount.abs());
                cTurnover.setOrderActPay(amount.abs());
                cTurnover.setUpdateTime(currentTime);
                cTurnover.setCreateTime(currentTime);
                cTurnover.setStatus(AccTurnoverStatusEnum.DONE.getValue());// 添加状态 30提现失败流水状态完成
                list.add(cTurnover);
                this.getcAccntTurnOverService().addDetailsAndLedger(list, 0); // TODO TODO
            } catch (Exception e) {
                LOGGER.info("提现修改账户余额系统异常.");
                result.setSuccess(false);
                result.setMessage("修改余额,系统异常.");
                e.printStackTrace();
            }
        }
        return result;
    }

    // 更新账户余额表用户密码
    private int setAccntLedgerPwd(CBalance cBalance, String pwd) {
        LOGGER.info("setAccntLedgerPwd params : {}, {}", cBalance, pwd);
        Date currentTime = new Date();
        LOGGER.info("更新账户余额表用户密码.pwd:{}.", pwd);
        int updateCount = 0;
        try {
            cBalance.setPwd(pwd);
            cBalance.setUpdateTime(currentTime);
            updateCount = this.getCBalanceMapper().updateByPrimaryKeySelective(cBalance);
        } catch (Exception e) {
            LOGGER.error("设置提现密码异常.", e);
            e.printStackTrace();
        }
        return updateCount;
    }

    // 查询账户余额表用户信息
    public CBalance getAccntLedger(Long userId, int userType) {
        LOGGER.info("getAccntLedger params : {}, {}", userId, userType);
        return this.getcBalanceViewMapper().selectByIdAndUsertype(userId, userType);
    }

    // 用户密码 验证
    public Result<String> valPwdIsTrue(String pwd, Long userId, Integer userType) {
        LOGGER.info("validation user password params pwd : {}, userId : {}, userType :{}.", pwd, userId, userType);
        Result<String> result = new Result<>(true, "密码验证成功");
        CBalance cBalance = this.getAccntLedger(userId, userType);
        if (null == cBalance) {
            LOGGER.info("validation user password params pwd : {}, userId : {}, userType :{} cBalance is null.", pwd, userId, userType);
            result.setSuccess(false);
            result.setMessage("账户不存在");
            return result;
        }
        pwd = passwordEncoder.encodePassword(pwd, jwtAuthenticationFilter.getSecureKey());
        if (!pwd.equalsIgnoreCase(cBalance.getPwd())) {
            LOGGER.info("validation user password params pwd : {}, userId : {}, userType :{} pwd is false.", pwd, userId, userType);
            result.setSuccess(false);
            result.setMessage("提现密码不正确");
            return result;
        }
        return result;
    }

    // 用户余额 验证
    public Result<String> valBalance(BigDecimal amount, Long userId, Integer userType) {
        LOGGER.info("validation user balance params amount : {}, userId : {}, userType :{}.", amount, userId, userType);
        Result<String> result = new Result<>(true, "余额验证成功");
        CBalance cBalance = this.getAccntLedger(userId, userType);
        if (null == cBalance) {
            LOGGER.info("validation user password params pwd : {}, userId : {}, userType :{} cBalance is null.", amount, userId, userType);
            result.setSuccess(false);
            result.setMessage("账户不存在");
            return result;
        }
        BigDecimal withdrawalBalance = cBalance.getWithdrawalBalance();
        if (amount.compareTo(withdrawalBalance) == -1) {
            LOGGER.info("validation user password params pwd : {}, userId : {}, userType :{}, balance : {}, balance is less amount.", amount, userId, userType, withdrawalBalance);
            result.setSuccess(false);
            result.setMessage("余额不足");
            return result;
        }
        return result;
    }

    // 提现日为每周四 判断
    private Result<String> valWithdrawDay() {
        Result<String> result = new Result<>(true);
        // 普通提现 每周四提现
        String withdrawDay = "";
        List<BCode> codes = getCodeService().getBCodeByClassCode("WITHDRAWDAY");
        if (codes.size() > 0) {
            withdrawDay = codes.get(0).getCode();
        } else {
            withdrawDay = "星期四";
        }

        String weekOfDate = DateUtils.getWeekOfDate(new Date());
        if (!withdrawDay.equals(weekOfDate)) {
            LOGGER.info("账户提现日为每周四.");
            result.setSuccess(false);
            result.setMessage("账户提现日为每周四.");
            return result;
        }

        return result;
    }

    /**
     * 人送项目 司机提现申请
     *
     * @param cashPwd
     * @param amount
     * @return
     */
    @Override
    public Result<String> submitSettlementAppli(String cashPwd, BigDecimal amount) {
        LOGGER.info("sendbydriver submit settlement applicate params cashPwd : {}, amount : {}.", cashPwd, amount);
        Result<String> result = new Result<>(true, "提现申请已提交");
        try {
            // 普通提现 每周四提现
            Result<String> dayResult = this.valWithdrawDay();
            if (!dayResult.isSuccess()) {
                return dayResult;
            }

            // 查询当前用户
            UserShowVo userShowVo = this.getUserShowVo();
            if (null == userShowVo) {
                LOGGER.info("sendbydriver submit settlement applicate params cashPwd : {}, amount : {} currentuser is null.", cashPwd, amount);
                result.setSuccess(false);
                result.setMessage("当前登录账户不存在");
                return result;
            }
            Long userId = userShowVo.getId();
            Integer userType = userShowVo.getUserType();

            // 验证密码
            Result<String> pwdResult = this.valPwdIsTrue(cashPwd, userId, userType);
            if (!pwdResult.isSuccess()) {
                return pwdResult;
            }

            // 验证余额
            Result<String> balanceResult = this.valBalance(amount, userId, userType);
            if (!balanceResult.isSuccess()) {
                return balanceResult;
            }

            // 提现申请
            Result<String> billResult = this.getCAccntBillService().submitSettlementAppli(userId, userType);
            if (!billResult.isSuccess()) {
                return billResult;
            }
        } catch (Exception e) {
            LOGGER.error("sendbydriver submit settlement applicate params cashPwd : {}, amount : {}, error : {}.", cashPwd, amount, e);
            throw new BusinessException("提现申请异常");
        }
        return result;
    }

}